package com.cos.hospital.ui.main;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.tool.ULog;
import com.cos.hospital.tool.USnackbar;
import com.cos.hospital.tool.UTxt;

import butterknife.BindView;

public class MainActivity extends CheckAppVersionActivity {
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    private long mExitTime;
    //定义数组来存放Fragment界面
    private MainFragment[] fragmentArray;
    private FragmentManager supportFragmentManager;
    private int oldPotison;
    // 广播接收类
    private BroadcastReceiver mainBR = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            if (intent == null || UTxt.isEmpty(intent.getAction())) {
                return;
            }
            ULog.commonD("收到广播：" + intent.getAction());
            switch (intent.getAction()) {
                case Code.Broadcast.CutoverToReception://前往接诊管理:
                    cutover(0);
                    break;
                case Code.Broadcast.CutoverToCure://前往治疗管理:
                    cutover(1);
                    break;
                case Code.Broadcast.CutoverToPatient://前往患者管理:
                    cutover(2);
                    break;
                case Code.Broadcast.CutoverToUserCenter://前往个人中心:
                    cutover(3);
                    break;
            }
        }
    };

    private void cutover(int position) {
        TabLayout.Tab tab = tabLayout.getTabAt(position);
        if (tab != null) {
            tab.select();
        }
        if (oldPotison == position) {//因为切换时会自动刷新，所以这里判断一下，如果没切换则刷新一次
            fragmentArray[position].refresh();
        }
    }

    @Override
    protected int layout() {
        return R.layout.activity_main;
    }

    @Override
    protected void init() {
        supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = supportFragmentManager.beginTransaction();

        fragmentArray = new MainFragment[4];
        int[] iconIDArray = new int[]{R.drawable.tab_reception, R.drawable.tab_cure, R.drawable.tab_patient, R.drawable.tab_personal};
        String[] tabNameArray = new String[]{"接诊管理", "治疗管理", "患者管理", "个人中心"};

        fragmentArray[0] = Tab1Fragment.newInstance();
        ft.add(R.id.fl_main, fragmentArray[0]).commit();
        int count = fragmentArray.length;
        for (int i = 0; i < count; i++) {
            View inflate = View.inflate(this, R.layout.item_tab, null);
            ImageView iv = inflate.findViewById(R.id.iv);
            TextView tv = inflate.findViewById(R.id.tv);
            iv.setBackgroundResource(iconIDArray[i]);
            tv.setText(tabNameArray[i]);
            tabLayout.addTab(tabLayout.newTab().setCustomView(inflate));
        }
        getNewestVersionInfo();
    }

    @Override
    protected void logic() {
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                oldPotison = tab.getPosition();
                gogogo(oldPotison);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        //切换到其他Fragment的广播
        IntentFilter cutoverFilter = new IntentFilter();
        cutoverFilter.addAction(Code.Broadcast.CutoverToReception);//前往接诊管理
        cutoverFilter.addAction(Code.Broadcast.CutoverToCure);//前往治疗管理
        cutoverFilter.addAction(Code.Broadcast.CutoverToPatient);//前往患者管理
        cutoverFilter.addAction(Code.Broadcast.CutoverToUserCenter);//前往个人中心
        cutoverFilter.setPriority(100);
        registerReceiver(mainBR, cutoverFilter);
    }

    private void gogogo(int position) {
        FragmentTransaction ft = supportFragmentManager.beginTransaction();
        for (int i = 0; i < fragmentArray.length; i++) {
            if (i == position) {
                if (fragmentArray[i] == null) {
                    switch (i) {
                        case 1://
                            fragmentArray[i] = Tab2Fragment.newInstance();
                            break;
                        case 2://
                            fragmentArray[i] = new PatientFragment();
                            break;
                        case 3://
                            fragmentArray[i] = new UserCenterFragment();
                            break;
                    }
                    if (!fragmentArray[i].isAdded()){
                        ft.add(R.id.fl_main, fragmentArray[i]);
                    }
                } else {
                    ft.show(fragmentArray[i]);
                    fragmentArray[i].refresh();
                }
            } else {
                if (fragmentArray[i] != null) {
                    ft.hide(fragmentArray[i]);
                }
            }
        }
        ft.commitAllowingStateLoss();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                USnackbar.showWarning(this, "再按一次退出" + getString(R.string.app_name));
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);//注释掉，避免异常退出时Activity自动保存退出时的状态，导致Fragment重叠
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mainBR);
    }
}
